#!/usr/bin/env python
#coding=utf-8
from google.appengine.ext import db
import base64, xxtea, re, phpformat, hashlib
from sso.mail import send_verify_mail
from sso.Config import Config
from time import time
from response_code import *
PASSWD_ENC_KEY = 'QWERTYUIOP!@#$%^bawbaw&*(?><MNBVhuCXZ@'


class Member(db.Model):
    username = db.StringProperty(required=True)
    password = db.StringProperty(required=True)
    email = db.StringProperty(required=True)
    reg_time = db.DateTimeProperty(auto_now_add=True)
    status = db.IntegerProperty(default = 0)

def is_username(username):
    if re.search("^[a-zA-Z0-9]{3,20}$", username):
    	return True
    else:
    	return False
def is_email(email):
    if re.search(r"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9\-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9\-]*[a-z0-9])?", email):
        return True
    else:
        return False
def is_password(passwd):
    if re.search("^[a-zA-Z0-9]{6,20}$", passwd):
    	return True
    else:
    	return False
def gen_password(passwd):
    return base64.b64encode(xxtea.encrypt(passwd, PASSWD_ENC_KEY))
def check(account):
    if is_email(account):
        return check_email(account)
    else:
        return check_username(account)
def check_email(account):
    member = Member.gql("where email = :1", account).get()
    if member is None:return HTTP_RESPONSE_EMAIL_NOT_EXISTS
    return HTTP_RESPONSE_EMAIL_EXISTS
def check_username(account):
    member = Member.gql("where username = :1", account).get()
    if member is None:return HTTP_RESPONSE_USERNAME_NOT_EXISTS
    return HTTP_RESPONSE_USERNAME_EXISTS
    
#reg new member
def reg(username, password, email):
    "register"
    password = str(password)
    username = str(username)
    if not is_username(username):return HTTP_RESPONSE_USERNAME_NO
    if not is_email(email):return HTTP_RESPONSE_EMAIL_NO
    if not is_password(password):return HTTP_RESPONSE_PASSWORD_NO
    if check_email(email) == HTTP_RESPONSE_EMAIL_EXISTS:return HTTP_RESPONSE_EMAIL_EXISTS
    if check_username(username) == HTTP_RESPONSE_USERNAME_EXISTS:return HTTP_RESPONSE_USERNAME_EXISTS
    member = Member(key_name = email,
                    username = username,
                    password = gen_password(password),
                    email = email)
    member.put()
    user = {"email": email, "username": username}
    send_verify_mail(user)
    return HTTP_RESPONSE_REGISTER_OK
def verify_mail(email, verify):
    "verify code"
    mail_conf = Config.get_instance()['mail']
    enc_data = mail_conf['enc_key']+email
    v = hashlib.md5(enc_data).hexdigest()
    if v != verify:return HTTP_RESPONSE_VALIDATE_NO
    member = Member.gql("where email = :1", email).get()
    if member is None:return HTTP_RESPONSE_EMAIL_NOT_EXISTS
    member.status = 1
    member.put()
    return HTTP_RESPONSE_VALIDATE_OK
def login(account, password):
    "login"
    account = account
    password = password
    passwd = gen_password(password)
    if is_email(account):       
        member = Member.gql("where email = :1", account).get()
        if member is None:return {'code':HTTP_RESPONSE_EMAIL_NOT_EXISTS}
        
    else:
        member = Member.gql("where username = :1", account).get()
        if member is None:return {'code':HTTP_RESPONSE_USERNAME_NOT_EXISTS}
        
    db_passwd = member.password
    if db_passwd != passwd:return {'code':HTTP_RESPONSE_PASSWORD_NO}
    status = member.status
    if status == 0:return {'code':HTTP_RESPONSE_VALIDATE_NO}
    info = {'code':HTTP_RESPONSE_LOGIN_OK}
    info['lists'] = []
    user = {'mail': member.email.encode('utf-8'), 
                    'username': member.username.encode('utf-8'), 
                    'time': str(member.reg_time),
                    'id': str(member.key())}
    unix_time = str(time())
    serialize_user = phpformat.serialize(user)
    for site in Config.get_instance()['sites']:
        url = site['url']
        key = site['key']
        array = {}
        array['info'] = serialize_user
        array['time'] = unix_time
        array['sign'] = hashlib.md5(key + serialize_user + unix_time).hexdigest()
        array['url'] = url
        info['lists'].append(array)
    return info
def logout():
    "logout"
    return [sites['url'] for sites in Config.get_instance()['sites']]
def update(email,new_password,session):
    "update password"
    if session['user']['mail'] is None:return HTTP_RESPONSE_VALIDATE_NO#please login
    session_mail = session['user']['mail']
    email = str(email)
    new_password = str(new_password)
    if session_mail != email:return HTTP_RESPONSE_VALIDATE_NO#please login
    if not is_password(new_password):return HTTP_RESPONSE_PASSWORD_NO
    member = Member.get_by_key_name(email)
    if member is None:return HTTP_RESPONSE_EMAIL_NOT_EXISTS
    member.password = gen_password(new_password)
    member.put()
    return HTTP_RESPONSE_UPDATE_OK
def delete():
    pass    